﻿package com.hanmanyi.scanning.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.UUID;

import sun.misc.BASE64Decoder;

/**
 * This is a helper class for file read&write operate
 * @author 帮杰
 *
 */
public class FileUtil {

	public static void append(File file,String content) throws IOException {
		FileWriter fw = new FileWriter(file, true);
		PrintWriter pw = new PrintWriter(fw);
		pw.print(content);
		pw.flush();
		fw.flush();
		pw.close();
		fw.close();
	}
	
    public static String readTextFile(File file) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        StringBuffer buffer = new StringBuffer();
        String s = null;
        while ((s = reader.readLine()) != null) {
            buffer.append(s).append("\r\n");
        }
        reader.close();
        return buffer.toString();
    }
    
    public static void copyFile(File sourceFile, File targetFile) throws IOException {
    	if(!targetFile.exists())
    		targetFile.createNewFile();
        BufferedInputStream inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
        BufferedOutputStream outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
        byte[] b = new byte[1024 * 5];
        int len;
        while ((len = inBuff.read(b)) != -1) {
            outBuff.write(b, 0, len);
        }
        outBuff.flush();
        outBuff.close();
        inBuff.close();
    }
    
    /**
	 *bas64转图片
	 * @param BASE64str bas64字符串
	 * @param path 存储地址
	 * @param ext 图片后缀
	 * @return 存储地址
	 */
	public static String BASE64CodeToBeImage(String BASE64str,String path,String ext){
		File fileDir = new File(path);
		if (!fileDir.exists()) {
			fileDir.setWritable(true);
			fileDir.mkdirs();
		}
        //文件名称
		String uploadFileName = UUID.randomUUID().toString() + "."+ext;
		File targetFile = new File(path, uploadFileName);
		BASE64Decoder decoder = new BASE64Decoder();
		try(OutputStream out = new FileOutputStream(targetFile)){
			byte[] b = decoder.decodeBuffer(BASE64str);
			for (int i = 0; i <b.length ; i++) {
				if (b[i] <0) {
					b[i]+=256;
				}
			}
			out.write(b);
			out.flush();
			return  path+"/"+uploadFileName+"."+ext;
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}


    public static void main(String[] args) throws IOException {
//    	copyFile(new File("C:/Users/帮杰/Desktop/test/math.doc"), new File("C:/Users/帮杰/Desktop/test/copyOf_math.doc"));
    	String base64 = "";
    	base64 = base64.replace("data:image/jpeg;base64,", "");
    	String filePath = "D:\\";
    	BASE64CodeToBeImage(base64, filePath,"jpg");
	}
}
